<template>
  <el-dialog
    :title="title+'开票'"
    append-to-body
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="form" class="myform" :rules="rules" :model="form" label-width="120px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="开票申请编号" prop="no">
            <el-input v-model="form.no" disabled placeholder="根据规则自动生成" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所有人" prop="owner">
            <el-input v-model="form.owner" readonly disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名" prop="customerId">
            <VbSelect v-model="form.customerId" :name="form.customerName" style="width:100%" :load-data="loadData" @change="handleChangeCustomer" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="单据状态" prop="status">
            <el-select v-model="form.status" disabled style="width:100%">
              <el-option v-for="cs in invoiceStatus" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractId">
            <VbSelect v-model="form.contractId" :name="form.contractNo" style="width:100%" :load-data="loadContractData" @change="handleChangeContract" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input v-model="form.contractAmount" disabled placeholder="" maxlength="13" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目/订单编号" prop="orderId">
            <VbSelect v-model="form.orderId" :name="form.orderNo" style="width:100%" :load-data="loadOrderData" @change="handleChangeOrder" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票金额（元）" prop="amount">
            <el-input v-model="form.amount" v-checkMoney placeholder="请输入开票金额" maxlength="13" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票日期" prop="date">
            <el-date-picker
              v-model="form.date"
              style="width:100%"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票类型" prop="type">
            <el-select v-model="form.type" style="width:100%">
              <el-option v-for="cs in invoiceTypes" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抬头类型" prop="riseType">
            <el-select v-model="form.riseType" style="width:100%">
              <el-option :value="1" label="单位" />
              <el-option :value="2" label="个人" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纳税识别码" prop="identifyCode">
            <el-input v-model="form.identifyCode" placeholder="请输入纳税识别码" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票抬头" prop="rise">
            <el-input v-model="form.rise" placeholder="请输入开票抬头" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户行" prop="bank">
            <el-input v-model="form.bank" placeholder="请输入开户行" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开户账号" prop="account">
            <el-input v-model="form.account" placeholder="请输入开户账号" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="开票地址" prop="addressId">
            <!-- <el-input v-model="form.addressId" placeholder="请输入开票地址" maxlength="100" /> -->
            <el-select v-model="form.addressId" style="width:100%">
              <el-option v-for="cs in invoiceList" :key="cs.value" :value="cs.value" :label="cs.label" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入电话" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contacts">
            <el-input v-model="form.contacts" placeholder="请输入联系人" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactsMode">
            <el-input v-model="form.contactsMode" placeholder="请输入联系方式" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮寄地址" prop="mailAddress">
            <el-input v-model="form.mailAddress" placeholder="请输入邮寄地址" maxlength="255" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="省市区" prop="areas">
            <RegionSelect v-model="form.areas" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="form.address" maxlength="255" placeholder="请输入地址" />
          </el-form-item>
        </el-col> -->

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="255" placeholder="请输入备注" :rows="4" />
          </el-form-item>

        </el-col>
      </el-row>
      <el-row style="text-align:right">
        <el-button plain @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-row>
    </el-form>

  </el-dialog>
</template>
<script>
import dayjs from 'dayjs'
// import RegionSelect from '@/components/RegionSelect'
import { invoiceStatus, invoiceTypes } from '@/utils/enums'
import { updateInvoice, saveInvoice } from '@/api/invoice'
import { getCustomerSelect, getCustomer } from '@/api/customer'
import { getContractSelect, getContract } from '@/api/contract'
import { getOrderSelect, getOrder } from '@/api/order'
import BigNumber from 'bignumber.js'

export default {
  name: 'AddClueDialog',
  components: { },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    }

  },
  data() {
    return {
      invoiceStatus,
      invoiceTypes,
      invoiceList: [],
      form: {
        'account': '',
        'address': '',
        'amount': '',
        'bank': '',
        'contacts': '',
        'contactsMode': '',
        'contractId': '',
        'contractNo': '',
        'customerId': '',
        customerName: '',
        'date': dayjs(),
        'identifyCode': '',
        'orderId': '',
        'orderNo': '',
        'phone': '',
        'remark': '',
        'rise': '',
        'riseType': '',
        'status': 1,
        'type': 1,
        addressId: '',
        contractAmount: '',
        owner: ''

      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        customerId: [
          { required: true, message: '客户名不能为空', trigger: 'blur' }
        ],
        contractId: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
        date: [
          { required: true, message: '开票时间不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '开票金额不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.data.id ? '修改' : '新建'
    }
  },
  mounted() {
    if (this.data.id) {
      // 修改
      if (this.data.province) {
        this.data.areas = [this.data.province, this.data.city, this.data.county]
      }
      this.form = JSON.parse(JSON.stringify(this.data))
      this.form.amount = BigNumber(this.form.amount || 0).toFixed(2)
      getCustomer({ id: this.data.customerId }).then(res => {
        this.invoiceList = res.invoiceList.map(m => {
          return {
            value: m.id,
            label: `${m.province}${m.city}${m.county}${m.address}`
          }
        }) || []
      })
    } else {
      this.form.owner = this.USER.userName
      console.log(' this.$route.query.customerId:', this.data)
      console.log('JSON.parse(JSON.stringify(this.data):', JSON.parse(JSON.stringify(this.data)))
      this.form = {
        ...this.form,
        ...JSON.parse(JSON.stringify(this.data))
      }
      if (this.form.customerId) {
        this.handleChangeCustomer({ id: this.form.customerId })
      }
    }
  },
  methods: {
    loadData(params) {
      return getCustomerSelect(params).then(res => {
        return res
      })
    },
    loadContractData(params) {
      return getContractSelect(params).then(res => {
        return res
      })
    },
    handleChangeCustomer(v) {
      this.form.addressId = ''
      getCustomer({ id: v.id }).then(res => {
        this.invoiceList = res.invoiceList.map(m => {
          return {
            value: m.id,
            label: `${m.province}${m.city}${m.county}${m.address}`
          }
        }) || []
      })
    },
    handleChangeOrder(v) {
      getOrder({ id: v.id }).then(res => {
        this.form.amount = BigNumber(res.amount || 0).toFixed(2)
        this.form.orderNo = res.no
      })
    },
    handleChangeContract(v) {
      getContract({ id: v.id }).then(res => {
        this.form.contractAmount = BigNumber(res.amount || 0).toFixed(2)
        this.form.contractNo = res.number
      })
    },
    loadOrderData(params) {
      return getOrderSelect(params).then(res => {
        return res
      })
    },
    handleClose() {
      this.$emit('close')
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 处理省市区
          if (this.form.areas && this.form.areas.length > 0) {
            this.form.province = this.form.areas[0]
            this.form.city = this.form.areas[1]
            this.form.county = this.form.areas[2]
          }
          // 有id 是修改
          if (this.data.id) {
            updateInvoice(this.form).then(res => {
              this.$emit('close', true)
              this.$message({
                type: 'success',
                message: '修改成功'
              })
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '修改失败'
              })
            })
          } else {
            saveInvoice(this.form).then(res => {
              this.$emit('close', true)
              this.$message({
                type: 'success',
                message: '新增成功'
              })
            }).catch(ex => {
              this.$message({
                type: 'error',
                message: ex.message || '新增失败'
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.myform{
  padding: 0 20px;
}
</style>
